package com.zhima.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.zhima.exception.ZhimaMinioException;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDateTime;

public class ZhimaMinioUtil {
    public static final String EXTENSION_SEPARATOR = ".";

    public static String getFileExtension(String fileName) throws ZhimaMinioException {
        if (fileName == null) {
            throw new ZhimaMinioException("文件名为空");
        }
        int indexOfSeparator = fileName.lastIndexOf(EXTENSION_SEPARATOR);
        if (indexOfSeparator == -1) {
            // 文件没有拓展名
            throw new ZhimaMinioException("文件没有拓展名!");
        }
        return fileName.substring(indexOfSeparator);
    }

    public static String todayFolder() {
        return DateUtil.format(LocalDateTime.now(), "yyyy/MM/dd/");
    }

    public static String getObjectName(String fileExtension, byte[] bytes) {
        return getObjectName(fileExtension, DigestUtil.md5Hex(bytes));
    }

    public static String getObjectName(String fileExtension, String fileMd5) {
        return ZhimaMinioUtil.todayFolder() + fileMd5 + fileExtension;
    }

    public static String getObjectName(String fileAbsolutePath) throws ZhimaMinioException {
        File file = new File(fileAbsolutePath);
        if (!file.exists()) {
            throw new ZhimaMinioException("文件不存在");
        }
        try (FileInputStream fis = new FileInputStream(file)) {
            return getObjectName(getFileExtension(file.getName()), fis.readAllBytes());
        } catch (IOException e) {
            throw new ZhimaMinioException(e, "文件读取失败");
        }
    }

    public static String getChunkFileFolder(String fileMd5, String chunkFolderName) {
        String nowFolder = todayFolder();
        String firstLevel = fileMd5.substring(0, 1);
        String secondLevel = fileMd5.substring(1, 2);
        return nowFolder + firstLevel + "/" + secondLevel + "/" + chunkFolderName + "/";
    }
}
